package org.example.springbook1.service;

import lombok.extern.slf4j.Slf4j;
import org.example.springbook1.enums.BookStatusEnum;
import org.example.springbook1.mapper.BookInfoMapper;
import org.example.springbook1.model.BookInfo;
import org.example.springbook1.model.PageRequest;
import org.example.springbook1.model.PageResult;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;

@Slf4j
@Service
public class BookService {

    @Autowired
    private BookInfoMapper bookInfoMapper;


    public PageResult<BookInfo> selectBookListByPage(PageRequest pageRequest) {
        if (pageRequest == null) {
            return null;
        }

        Integer count = bookInfoMapper.count();
        List<BookInfo> bookInfos = bookInfoMapper.selectBookInfoByPage(pageRequest.getOffset(), pageRequest.getPageSize());

        if (bookInfos != null && bookInfos.size() > 0) {
            for (BookInfo bookInfo : bookInfos) {
                bookInfo.setStatusCN(BookStatusEnum.getNameByCode(bookInfo.getStatus()).getName());

            }
        }
        return new PageResult<>(bookInfos, count, pageRequest);
    }

    public Integer addBook(BookInfo bookInfo) {
        Integer result = 0;
        try {
            result = bookInfoMapper.insertBook(bookInfo);

        } catch (Exception e) {
            log.error("添加图书出错，error:{}", e);
        }
        return result;
    }

    public BookInfo queryBookById(Integer id){
        return bookInfoMapper.queryBookById(id);
    }

    public Integer updateBook(BookInfo bookInfo) {
        Integer result = 0;
        try{
            result = bookInfoMapper.updateBook(bookInfo);
        } catch (Exception e) {
            log.error("更新图书失败error:{}", e);
        }
        return result;
    }

    public Integer batchDelete(List<Integer> ids) {
        Integer result = 0;
        try{
            result = bookInfoMapper.batchDelete(ids);
        }catch (Exception e) {
            e.printStackTrace();
            log.error("批量删除图书失败，ids：{}",ids);
        }
        return result;
    }

}
